package com.swy.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

@Configuration
@EnableWebSecurity
public class SecurityConfig {
    private static final Logger log = LoggerFactory.getLogger(SecurityConfig.class);

    @Value("${app.author.file:author/config.properties}") // 从application.yml或默认值读取作者文件路径
    private String authorFilePath;

    @Value("${app.admin.username:admin}") // 从application.yml读取默认用户名
    private String defaultUsername;

    @Value("${app.admin.password:123456}") // 从application.yml读取默认密码
    private String defaultPassword;

    private InMemoryUserDetailsManager userDetailsManager;
    private final AuthenticationConfiguration authenticationConfiguration;

    public SecurityConfig(AuthenticationConfiguration authenticationConfiguration) {
        this.authenticationConfiguration = authenticationConfiguration;
    }

    @Bean
    public UserDetailsService userDetailsService() {
        log.info("初始化 UserDetailsService");
        userDetailsManager = createUserDetailsManager();
        return userDetailsManager;
    }

    private InMemoryUserDetailsManager createUserDetailsManager() {
        String username = defaultUsername;
        String password = defaultPassword;

        // 尝试从author/config.properties加载用户
        File authorFile = new File(authorFilePath);
        if (authorFile.exists() && authorFile.isFile()) {
            Properties props = new Properties();
            try (FileInputStream fis = new FileInputStream(authorFile)) {
                props.load(fis);
                String fileUsername = props.getProperty("username"); // 读取username
                String filePassword = props.getProperty("password"); // 读取password
                if (fileUsername != null && !fileUsername.trim().isEmpty() && filePassword != null && !filePassword.trim().isEmpty()) {
                    username = fileUsername.trim();
                    password = filePassword.trim();
                    log.info("从 author/config.properties 加载用户成功: username={}", username);
                } else {
                    log.warn("author/config.properties 文件内容无效，使用 application.yml 中的默认用户。");
                }
            } catch (IOException e) {
                log.error("读取 author/config.properties 文件出错，使用 application.yml 中的默认用户: {}", e.getMessage());
            }
        } else {
             log.warn("author/config.properties 文件不存在或不是文件，使用 application.yml 中的默认用户。");
        }

        // 创建内存用户
        UserDetails user = User.builder()
                .username(username)
                .password(password)
                .roles("ADMIN") // 可以定义角色
                .build();

        log.info("创建用户: username={}", username);
        return new InMemoryUserDetailsManager(user);
    }

    public void reloadUsers() {
        log.info("开始重新加载用户配置");
        if (userDetailsManager != null) {
            // 获取当前配置的用户名
            String currentUsername = defaultUsername;
            String currentPassword = defaultPassword;
            File authorFile = new File(authorFilePath);
            if (authorFile.exists() && authorFile.isFile()) {
                Properties props = new Properties();
                try (FileInputStream fis = new FileInputStream(authorFile)) {
                    props.load(fis);
                    String fileUsername = props.getProperty("username");
                    String filePassword = props.getProperty("password");
                    if (fileUsername != null && !fileUsername.trim().isEmpty()) {
                        currentUsername = fileUsername.trim();
                        currentPassword = filePassword.trim();
                        log.info("从配置文件读取到用户名: {}", currentUsername);
                        log.info("从配置文件读取到密码: {}", currentPassword);
                    }
                } catch (IOException e) {
                    log.error("读取 author/config.properties 文件出错: {}", e.getMessage());
                }
            }
            
            // 删除现有用户
            log.info("删除现有用户: {}", currentUsername);
            userDetailsManager.deleteUser(currentUsername);
            
            // 创建新用户
            log.info("创建新用户: username={}", currentUsername);
            UserDetails newUser = User.builder()
                    .username(currentUsername)
                    .password(currentPassword)
                    .roles("ADMIN")
                    .build();
            
            // 添加新用户
            userDetailsManager.createUser(newUser);
            log.info("新用户创建成功");
            
            log.info("用户配置重新加载完成");
        } else {
            log.warn("userDetailsManager 为空，无法重新加载用户");
        }
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        // WARNING: NoOpPasswordEncoder is NOT recommended for production.
        // Use a strong hashing algorithm like BCryptPasswordEncoder instead.
        return NoOpPasswordEncoder.getInstance();
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeRequests(authorizeRequests ->
                authorizeRequests
                    .antMatchers("/detector/", "/detector/login", "/detector/check", "/static/**", "/detector/static/**").permitAll() // 允许匿名访问首页、登录页、检测接口和所有静态资源
                    .antMatchers("/detector/admin/**").hasRole("ADMIN") // /admin/** 路径需要ADMIN角色
                    .anyRequest().authenticated() // 其他所有请求都需要认证
            )
            .formLogin(formLogin ->
                formLogin
                    .loginPage("/detector/login") // 指定登录页面的URL
                    .loginProcessingUrl("/detector/login") // 处理登录表单提交的URL (对应POST)
                    .defaultSuccessUrl("/detector/admin/words", true) // 登录成功后重定向到敏感词管理页
                    .permitAll() // 登录相关的页面和处理允许所有访问
            )
            .logout(logout ->
                logout
                    .logoutUrl("/detector/logout") // 指定退出登录的URL (对应POST)
                    .logoutSuccessUrl("/detector/login?logout") // 退出成功后重定向到登录页
                    .permitAll()
            )
            .csrf().disable(); // 暂时禁用CSRF保护方便测试，生产环境应启用并 properly handled

        return http.build();
    }
} 